﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using Agricultural_Sales.CS;

namespace Agricultural_Sales.ASP
{
    public partial class MyUserInfo : System.Web.UI.Page
    {
        private string connectionString = ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // 检查用户是否登录
                if (Session["UserId"] == null)
                {
                    Response.Redirect("Login.aspx");
                    return;
                }

                LoadUserInfo();
                SetInitialState();
            }
        }

        private void SetInitialState()
        {
            // 初始状态：禁用编辑字段
            txtPhone.Enabled = false;
            txtAddress.Enabled = false;
        }

        private void LoadUserInfo()
        {
            try
            {
                int userId = Convert.ToInt32(Session["UserId"]);

                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();
                    string sql = "SELECT UserId, UserName, Phone, UserImagee, Address, UserType FROM Users WHERE UserId = @UserId";

                    using (SqlCommand cmd = new SqlCommand(sql, conn))
                    {
                        cmd.Parameters.AddWithValue("@UserId", userId);

                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                txtUserId.Text = reader["UserId"].ToString();
                                txtUserName.Text = reader["UserName"].ToString();
                                txtPhone.Text = reader["Phone"].ToString();
                                txtAddress.Text = reader["Address"].ToString();
                                txtUserTypeDisplay.Text = reader["UserType"].ToString();
                                lblUserType.Text = reader["UserType"].ToString();

                                // 设置头像
                                string imagePath = reader["UserImagee"].ToString();
                                if (!string.IsNullOrEmpty(imagePath))
                                {
                                    if (imagePath.StartsWith("~/"))
                                    {
                                        imgAvatar.ImageUrl = imagePath;
                                    }
                                    else
                                    {
                                        imgAvatar.ImageUrl = "~/" + imagePath;
                                    }
                                }
                                else
                                {
                                    imgAvatar.ImageUrl = "~/Image/default-avatar.png";
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage("加载用户信息失败：" + ex.Message, false);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证密码
                if (!string.IsNullOrEmpty(txtNewPassword.Text))
                {
                    if (txtNewPassword.Text != txtConfirmPassword.Text)
                    {
                        ShowMessage("两次输入的密码不一致！", false);
                        return;
                    }

                    if (txtNewPassword.Text.Length < 6)
                    {
                        ShowMessage("密码长度不能少于6位！", false);
                        return;
                    }
                }

                int userId = Convert.ToInt32(Session["UserId"]);
                string imagePath = null;

                // 处理头像上传
                if (fileAvatar.HasFile)
                {
                    try
                    {
                        Upload_Image uploadHelper = new Upload_Image();
                        imagePath = uploadHelper.uploadimg(fileAvatar);

                        if (string.IsNullOrEmpty(imagePath))
                        {
                            ShowMessage("头像上传失败！", false);
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        ShowMessage("头像上传失败：" + ex.Message, false);
                        return;
                    }
                }

                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();
                    string sql;

                    if (!string.IsNullOrEmpty(txtNewPassword.Text))
                    {
                        // 更新包括密码在内的所有信息
                        sql = @"UPDATE Users SET Phone = @Phone, Address = @Address, Password = @Password";
                        if (!string.IsNullOrEmpty(imagePath))
                        {
                            sql += ", UserImagee = @UserImagee";
                        }
                        sql += " WHERE UserId = @UserId";
                    }
                    else
                    {
                        // 更新除密码外的信息
                        sql = @"UPDATE Users SET Phone = @Phone, Address = @Address";
                        if (!string.IsNullOrEmpty(imagePath))
                        {
                            sql += ", UserImagee = @UserImagee";
                        }
                        sql += " WHERE UserId = @UserId";
                    }

                    using (SqlCommand cmd = new SqlCommand(sql, conn))
                    {
                        cmd.Parameters.AddWithValue("@Phone", txtPhone.Text.Trim());
                        cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());
                        cmd.Parameters.AddWithValue("@UserId", userId);

                        if (!string.IsNullOrEmpty(txtNewPassword.Text))
                        {
                            cmd.Parameters.AddWithValue("@Password", txtNewPassword.Text);
                        }

                        if (!string.IsNullOrEmpty(imagePath))
                        {
                            cmd.Parameters.AddWithValue("@UserImagee", imagePath);
                        }

                        int result = cmd.ExecuteNonQuery();

                        if (result > 0)
                        {
                            ShowMessage("信息更新成功！", true);

                            // 清空密码框
                            txtNewPassword.Text = "";
                            txtConfirmPassword.Text = "";

                            // 重新加载用户信息
                            LoadUserInfo();

                            // 退出编辑模式
                            string script = @"
                                isEditMode = false;
                                document.getElementById('" + txtPhone.ClientID + @"').disabled = true;
                                document.getElementById('" + txtAddress.ClientID + @"').disabled = true;
                                document.getElementById('passwordSection').style.display = 'none';
                                document.getElementById('" + btnEdit.ClientID + @"').style.display = 'inline-block';
                                document.getElementById('editButtons').style.display = 'none';
                            ";
                            ClientScript.RegisterStartupScript(this.GetType(), "ExitEditMode", script, true);
                        }
                        else
                        {
                            ShowMessage("信息更新失败！", false);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage("更新失败：" + ex.Message, false);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            // 重新加载原始信息
            LoadUserInfo();

            // 清空密码框
            txtNewPassword.Text = "";
            txtConfirmPassword.Text = "";

            ShowMessage("已取消修改！", true);
        }

        private void ShowMessage(string message, bool isSuccess)
        {
            lblMessage.Text = message;
            lblMessage.CssClass = isSuccess ? "success-message" : "error-message";
            pnlMessage.Visible = true;

            // 使用JavaScript在3秒后隐藏消息
            string script = $"setTimeout(function(){{ document.getElementById('{pnlMessage.ClientID}').style.display='none'; }}, 3000);";
            ClientScript.RegisterStartupScript(this.GetType(), "HideMessage", script, true);
        }
    }
}